package com.study.cglib;

import com.study.entity.User;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class TestCglib {

    public static void main(String[] args) {
        // 1. 创建原始对象
        UserService userService = new UserService();

        /**
         * 2. 通过cglib方式创建动态代理对象
         * Proxy.newProxyInstance(classloader, interface, invocationHandler);
         *
         * 需要 ClassLoader、父类、额外功能
         *
         * setClassLoader
         * setSuperclass
         * setCallback  ---> MethodInterceptor
         * create() --> 代理
         *
         */
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(TestCglib.class.getClassLoader());
        enhancer.setSuperclass(UserService.class);

        MethodInterceptor interceptor = new MethodInterceptor() {
            // 等同于 InvocationHandler.invoke
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("---cglib log---");
                Object invoke = method.invoke(userService, objects);
                return invoke;
            }
        };
        enhancer.setCallback(interceptor);

        UserService userServiceProxy = (UserService) enhancer.create();
        userServiceProxy.login("zhangsan", "888");
        userServiceProxy.register(new User());
    }
}
